package org.traffometer.traffobase.server;

import org.apache.derby.drda.NetworkServerControl;
import org.traffometer.traffobase.model.FilePacketStore;
import org.traffometer.traffobase.model.PacketStore;

/**
 * Starts the TraffoBase server.
 * 
 * @author Robert S. Brewer
 */
public class Main {

  /**
   * Empty constructor as this class is never intended to be instantiated, but this keeps
   * PMD et al happy.
   */
  private Main() {
    // empty constructor as this class is never intended to be instantiated.
  }
  
  /**
   * Starts the TraffoBase server.
   * 
   * @param args holds command line arguments.
   */
  public static void main(String[] args) {
    NetworkServerControl server;
    try {
      server = new NetworkServerControl();
      server.start (null);
      System.out.println("Derby has been started!");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    String defaultPacketStoreName = "PacketStore";
    String packetStoreName = defaultPacketStoreName;
    String serverInterface = "";
    int port = -1;

    for (int i = 0; i < args.length; i++) {
      if ("-interface".equals(args[i])) {
        serverInterface = args[i + 1];
      }
      else if ("-port".equals(args[i])) {
        try {
          port = Integer.parseInt(args[i + 1]);
        }
        catch (NumberFormatException e) {
          System.err.println("Invalid port number specified, exiting.");
          return;
        }
      }
      else if ("-store".equals(args[i])) {
        packetStoreName = args[i + 1];
      }
    }

    if ("".equals(serverInterface)) {
      System.err.println("No server interface specified, will use default.");
    }
    if (port == -1) {
      System.err.println("No server port specified, will use default.");
    }
    if (defaultPacketStoreName.equals(packetStoreName)) {
      System.err.println("No packet store name specified, will use default.");
    }
    PacketStore packetStore = new FilePacketStore(packetStoreName);
    System.out.println("Opened packet store from " + packetStoreName);
    PacketListener packetListener = new PacketListener(serverInterface, port, packetStore);
    packetListener.listen();
  }

}
